package wangyiyunclass.io.demo8;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 利用序列化 和 反序列化 实现深拷贝
 */
public class DeepCopy {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 创建学生对象
        Student stu1 = new Student("张三", 20, new ArrayList<>());
        stu1.grades.add(79);
        stu1.grades.add(81);
        stu1.grades.add(99);
        Student stu2 = deepCopy(stu1);
        System.out.println("----------- 拷贝 stu1 后 ---------------");
        System.out.println("stu1: " + stu1); // stu1: [name='张三', age=20, grades=[79, 81, 99]]
        System.out.println("stu2: " + stu2); // stu2: [name='张三', age=20, grades=[79, 81, 99]]
        System.out.println("----------- 修改 stu2 后 ---------------");
        stu2.name = "李四";
        stu2.age = 21;
        stu2.grades.clear();
        stu2.grades.add(82);
        stu2.grades.add(73);
        stu2.grades.add(92);
        System.out.println("stu1: " + stu1); // stu1: [name='张三', age=20, grades=[79, 81, 99]]
        System.out.println("stu2: " + stu2); // stu2: [name='李四', age=21, grades=[82, 73, 92]]
    }
    public static Student deepCopy(Student stu) throws IOException, ClassNotFoundException {
        // 创建文件，用于写序列化后的字节
        File file = new File("student.txt");
        // 创建对象序列化流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(stu);
        oos.close();
        // 创建对象反序列化流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Student newStu = (Student) ois.readObject();
        ois.close();
        // 删除文件
        file.deleteOnExit();
        return newStu;
    }
}

class Student implements Serializable {
    public String name;
    public int age;
    public List<Integer> grades;

    public Student(String name, int age, List<Integer> grades) {
        this.name = name;
        this.age = age;
        this.grades = grades;
    }

    @Override
    public String toString() {
        return "[" + "name='" + name + '\'' + ", age=" + age + ", grades=" + grades + ']';
    }
}